<?php
class dbstuff {
	var $querynum = 0;
	var $queries = array();
	var $version = '';
	var $charset = '';
	var $dbhost = '';
	var $dbuser = '';
	var $dbpw = '';
	var $dbname = '';
	var $connect;
	function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = '') {
		global $pconnect;
		if((!isset($pconnect) || $pconnect == 1) && function_exists('mysql_pconnect')) {
			if(!$connect = mysql_pconnect($dbhost, $dbuser, $dbpw)) {
				$this->halt('Can not connect to MySQL server');
			}
		} else {
			if(!$connect = mysql_connect($dbhost, $dbuser, $dbpw)) {
				$this->halt('Can not connect to MySQL server');
			}
		}
		$version = mysql_get_server_info();
		$this->charset = $charset;
		$this->version = $version;
		$this->dbhost = $dbhost;
		$this->dbuser = $dbuser;
		$this->dbpw = $dbpw;
		$this->dbname = $dbname;
		if($version > '4.1') mysql_query("SET NAMES '{$charset}'", $connect);
		if($version > '5.0') mysql_query("SET sql_mode=''", $connect);
		if($dbname) mysql_select_db($dbname, $connect);
		$this->connect = $connect;
	}

	function fetch_array($query, $result_type = MYSQL_ASSOC) {
		return mysql_fetch_array($query, $result_type);
	}

	function query($sql) {
		global $ifdebug, $slowquery;
		mysql_select_db($this->dbname, $this->connect);
		if(!empty($ifdebug)) $start = akmicrotime();
		if(!$query = @mysql_query($sql, $this->connect)) $this->halt($this->error(), $sql);
		if(!empty($ifdebug)) {
			$usedtime = akmicrotime() - $start;
			if(empty($slowquery) || $usedtime > $slowquery) {
				error_log($sql."(".msformat(akmicrotime() - $start).")\n", 3, AK_ROOT.'logs/queries');
			}
		}
		$this->querynum++;
		if($this->querynum < 20) $this->queries[] = $sql;
		return $query;
	}

	function querytoarray($sql, $num = 1000) {
		$results = array();
		$query = $this->query($sql);
		$i = 1;
		while($row = $this->fetch_array($query)) {
			$results[] = $row;
			if($i ++ >= $num) break;
		}
		return $results;
	}

	function close() {
		global $db, $mysqldb;
		@mysql_close($this->connect);
		unset($db);
		unset($mysqldb);
	}

	function get_by($what, $from, $where = '') {
		$table = $this->fulltablename($from);
		$sql = "SELECT {$what} FROM {$table}";
		if($where != '') $sql .= " WHERE {$where}";
		if(strpos($what, '(') === false) $sql .= " LIMIT 1";
		$row = $this->get_one($sql);
		if($row === false) {
			return false;
		} elseif(count($row) == 1) {
			return current($row);
		} else {
			return $row;
		}
	}

	function list_by($what, $from, $where = '', $orderby = '', $limit = '') {
		$table = $this->fulltablename($from);
		$sql = "SELECT {$what} FROM {$table}";
		if($where != '') $sql .= " WHERE {$where}";
		if($orderby != '') $sql .= " ORDER BY {$orderby}";
		if(!empty($limit)) $sql .= " LIMIT {$limit}";
		return $this->query($sql);
	}

	function insert($table, $values) {
		$table = $this->fulltablename($table);
		$sql = "INSERT INTO {$table}";
		$keysql = '';
		$valuesql = '';
		foreach($values as $key => $value) {
			$keysql .= "`$key`,";
			$valuesql .= "'".ak_addslashes($value)."',";
		}
		$sql = $sql.'('.substr($keysql, 0, -1).')VALUES('.substr($valuesql, 0, -1).')';
		return $this->query($sql);
	}

	function update($table, $values, $where) {
		$table = $this->fulltablename($table);
		$sql = "UPDATE {$table} SET ";
		$keysql = '';
		$valuesql = '';
		foreach($values as $k => $v) {
			if(substr($v, 0, 1) == '+' && a_is_int(substr($v, 1))) {
				$sql .= "`$k`={$k}{$v},";
			} else {
				$sql .= "`$k`='".ak_addslashes($v)."',";
			}
		}
		$sql = substr($sql, 0, -1);
		$sql .= " WHERE {$where}";
		return $this->query($sql);
	}

	function delete($table, $where = '') {
		$table = $this->fulltablename($table);
		$sql = "DELETE FROM {$table}";
		if($where != '') $sql .= " WHERE {$where}";
		return $this->query($sql);
	}

	function get_one($sql) {
		$arr = $this->querytoarray($sql, 1);
		if(isset($arr[0])) {
			return $arr[0];
		} else {
			return false;
		}
	}

	function get_field($sql) {
		$arr = $this->get_one($sql);
		if(!empty($arr)) {
			return current($arr);
		} else {
			return '';
		}
	}

	function insert_id() {
		return mysql_insert_id($this->connect);
	}

	function getalltables() {
		$tables = array();
		$sql = "SHOW TABLES";
		$query = $this->query($sql);
		$tables = array();
		while($table = $this->fetch_array($query)) {
			$tables[] = current($table);
		}
		return $tables;
	}

	function getallfields($table) {
		$fields = array();
		$results = $this->querytoarray("EXPLAIN $table");
		foreach($results as $result) {
			$fields[] = $result['Field'];
		}
		return $fields;
	}

	function error() {
		return mysql_error($this->connect);
	}

	function halt($message = '', $sql = '') {
		debug($sql."\n".$message, 1);
	}
	
	function getcreatetable($table) {
		$sql = "SHOW CREATE TABLE `{$table}`";
		$result = current($this->querytoarray($sql));
		return $result['Create Table'];
	}
	function fulltablename($table) {
		global $tablepre;
		if(in_array($table, array('admins', 'attachments', 'captchas', 'categories', 'comments', 'filenames', 'item_exts', 'items', 'modules', 'scores', 'sections', 'settings', 'texts', 'variables', 'ses', 'keywords'))) {
			return $tablepre.'_'.$table;
		} else {
			return $table;
		}
	}
}
?>